// NetSocket class from BlackHoleMedia
// http://www.blackholemedia.com/
// Renamed to CantripSocket for CantripSDK
// Based on NetSocket v0.3

#import <Foundation/Foundation.h>
#import <netinet/in.h>

@interface CantripSocket : NSObject 
{
	CFSocketRef     mSocketRef;
	
	NSString*       mRemoteHost;
	UInt16		mRemotePort;
	
	BOOL		mConnected;
	BOOL		mListening;
	BOOL		mWritable;
	
	NSMutableData*	mWritableData;
	NSMutableData*	mReadableData;
	NSTimer*	mConnectTimer;
	
	id		mDelegate;
}

// Creation
+ (CantripSocket*)socket;
+ (CantripSocket*)socketListeningOnPort:(UInt16)inPort;
+ (CantripSocket*)socketConnectedToHost:(NSString*)inHost port:(UInt16)inPort;

// Delegate
- (id)delegate;
- (void)setDelegate:(id)inDelegate;

// Open / Close
- (BOOL)open;
- (void)close;

// Connecting
- (BOOL)connectToHost:(NSString*)inHost port:(UInt16)inPort;
- (BOOL)connectToHost:(NSString*)inHost port:(UInt16)inPort timeout:(NSTimeInterval)inTimeout;

// Listening
- (BOOL)listenOnPort:(UInt16)inPort;
- (BOOL)listenOnPort:(UInt16)inPort maxPendingConnections:(int)inMaxPendingConnections;

// Reading
- (unsigned)read:(void*)inBuffer amount:(unsigned)inAmount;
- (unsigned)readOntoData:(NSMutableData*)inData;
- (unsigned)readOntoData:(NSMutableData*)inData amount:(unsigned)inAmount;
- (unsigned)readOntoString:(NSMutableString*)inString encoding:(NSStringEncoding)inEncoding amount:(unsigned)inAmount;
- (NSData*)readData;
- (NSData*)readData:(unsigned)inAmount;
- (NSString*)readString:(NSStringEncoding)inEncoding;
- (NSString*)readString:(NSStringEncoding)inEncoding amount:(unsigned)inAmount;

// Writing
- (void)write:(const void*)inBytes amount:(unsigned)inAmount;
- (void)writeData:(NSData*)inData;
- (void)writeString:(NSString*)inString encoding:(NSStringEncoding)inEncoding;

// Peeking
- (const NSData*)peekData;

// Properties
- (const CFSocketRef)cfsocket;
- (NSString*)remoteHost;
- (UInt16)remotePort;
- (BOOL)opened;
- (BOOL)connected;
- (BOOL)listening;
- (BOOL)readable;
- (unsigned)readableByteCount;

// Utility
+ (NSString*)stringWithAddress:(struct in_addr*)inAddress;

@end

// NetSocket delegate is not required to implement any of the delegate methods.
@interface NSObject (CantripSocketDelegate)
- (void)socketConnected:(CantripSocket*)inSocket;
- (void)socketDisconnected:(CantripSocket*)inSocket;
- (void)socket:(CantripSocket*)inSocket connectionTimedOut:(NSTimeInterval)inTimeout;
- (void)socket:(CantripSocket*)inSocket newConnection:(CantripSocket*)inNewSocket;
- (void)socket:(CantripSocket*)inSocket dataAvailable:(unsigned)inAmount;
- (void)socketSentData:(CantripSocket*)inSocket;
@end
